package java_thinking.unit_21._21_6;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @Desc:   6-4 基于线程池的 web 服务器
 * @author: cww
 * @DateTime: 2019/6/11 8:45
 */

public class TaskExecutionWebServer {
    private static final int NTHREADS = 100;
    /**
     * 固定长度的线程池，每当提交一个任务时就创建一个线程，直到达到线程池的最大数量，这时
     * 线程池的规模将不再变化
     */
    private static final Executor exec = Executors.newFixedThreadPool(NTHREADS);
    public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(80);
        while (true) {
            final Socket connection = socket.accept();
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    handleRequest(connection);
                }
            };
            exec.execute(task);
        }
    }

    private static void handleRequest(Socket connection) {
        // request-handling logic here
    }
}
